<?php
namespace Zxf5115\Laravel\Resource\Services;

use InvalidArgumentException;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
use Zxf5115\Laravel\Resource\Models\Common\Resource;
use Illuminate\Database\Eloquent\ModelNotFoundException;

/**
 * @author zhangxiaofei [<1326336909@qq.com>]
 * @dateTime 2025-09-17
 *
 * 资源服务类
 */
class ResourceService
{
  /**
   * 根据哈希验证资源信息是否存在
   *
   * @param [type] $file 文件哈希值
   * @param boolean $is_filename 是否返回文件名
   * @return mixed
   */
  public static function verifyFileUploadCompleted(string $hash, bool $is_filename = false) : mixed
  {
    try
    {
      $model = Resource::byHash($hash)->firstOrFail();

      return $is_filename
           ? ['filename' => $model->name, 'url' => $model->url]
           : $model->url;
    }
    catch (ModelNotFoundException $e)
    {
      return null;
    }
  }


  /**
   * 保存平台文件信息
   *
   * @param array $params 资源参数
   */
  public static function setFileUploadCompleted(array $params) : void
  {
    // 1. 存储资源
    $model = Resource::firstOrNew(['hash' => $params['hash'], 'status' => 1]);
    $model->name = $params['name'];
    $model->size = $params['size'];
    $model->mimetype = $params['mimetype'];
    $model->extension = $params['extension'];
    $model->hash = $params['hash'];
    $model->url = $params['url'];

    if(!$model->save())
    {
      // 2. 抛异常替代静默失败，便于上层处理
      throw new InvalidArgumentException(__('resources.upload_failed'));
    }
  }
}
